<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>兼容classname获取DOM对象</title>
    <style>
    div{
        width: 50px;
        height: 30px;
        font-size: 18px;
    }
    .text{
        background:green;
    }
    .red{
        background:red;
    }
    .fff{
        color: #fff;
    }
    </style>
</head>
<body>
<div class="text">text</div>
<div class="red"></div>
<div class="red"></div>
<div class="text">text</div>
<div class="text red fff">fff</div>
<div class="text red fff">fff</div>
<div class="text red">text</div>
<div class="text red fff">fff</div>
<div class="red"></div>
<div class="text">text</div>

<script>
    function $c(className){
        if(document.getElementsByClassName){//如果可以用则直接用
            return document.getElementsByClassName(className);
        }
        //不可以用时：
        var arr = [];
        var dom = document.getElementsByTagName("*");
        for(var i=0;i<dom.length;i++){
            var text = dom[i].className.split(" ");//多个类名时字符串转化为数组
            // if(text.indexOf(className) != -1){//如果该数组存在该ClassName
            //     arr.push(dom[i])//加入arr
            // }
            for(var j=0;j<dom.length;j++){
                if(text[j]==className){
                    arr.push(dom[i])
                }
            }
        }
        return arr;
    }
    
    $c("text")[3].style.background = "blue";
    
</script>
</body>
</html>